package com.peng.leetcode.backtracking;

import java.util.*;

/**
 * Permute
 * 剑指 Offer II 083. 没有重复元素集合的全排列
 * https://leetcode.cn/problems/VvJkup/
 *
 * @author: lupeng6
 * @create: 2023/3/19 17:05
 */
public class Permute {

    /**
     * 输入：nums = [1,2,3]
     * 输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
     *
     * @author lupeng6
     * @date 2023/3/19 17:06
     */
    public static void main(String[] args) {
        List<List<Integer>> permute = new Permute().permute(new int[]{1, 2, 3});
        System.out.println(permute);
    }

    private boolean[] visited;

    public List<List<Integer>> permute(int[] nums) {
        if (nums == null || nums.length == 0) {
            return new ArrayList<>();
        }
        visited = new boolean[nums.length];
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        backtrack(nums, 0, new LinkedList<>(), ans);
        return ans;
    }


    private void backtrack(int[] nums, int index, LinkedList<Integer> q, List<List<Integer>> ans) {
        if (index == nums.length) {
            ans.add(new ArrayList<>(q));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            // index > 0 && nums[index] == nums[index - 1] && !visited[index - 1]
            // 1,1,1 这种情况值保证出现一次 1,1,1 这样的排列，防止产生多次
            if (visited[i] || (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1])) {
                continue;
            }
            visited[i] = true;
            q.addLast(nums[i]);
            backtrack(nums, index + 1, q, ans);
            visited[i] = false;
            q.removeLast();
        }
    }
}
